package org.itsky.study.test6;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author sky
 * @Site cmtianxie163.com 2020/4/18 23:01
 */
public class CallableTest {
    public static void main(String[] args) {
        MyCallable callable = new MyCallable();
        //将Callable接口实现类的对象作为参数传递到FutureTask构造器中，创建FutureTask的对象
        FutureTask<Integer> futureTask = new FutureTask<>(callable);

        //创建线程
        /**
         * 这里创建线程 Thread构造器传的参数实际上还是一个 Runnable实现类的对象
         * 因为FutureTask 实现了RunnableFuture接口 而RunnableFuture又实现了Runnable接口
         */

        Thread t1 = new Thread(futureTask);
        t1.start();
        //线程执行后，可以通过futureTask拿到call方法的返回值
        try {
            Integer sum = futureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}


class MyCallable implements Callable<Integer> {//泛型可不写 默认Object 对应的是call()方法的返回值类型

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 50; i++) {
            System.out.println(i);
            sum += i;
        }
        return sum;
    }
}